package redis

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/gomodule/redigo/redis"
)

var DefaultRedisConn redis.Conn
func init(){
	var err error
	DefaultRedisConn,err = redis.Dial("tcp",":6379")
	if err!=nil{
		panic("dial redis server failed:"+err.Error())
	}
}
func Set(key ,value string)error{
	if exists,_:=Exists(key);exists{
		return errors.New("key exists")
	}
	_,err:= DefaultRedisConn.Do("SET",key,value)
	return err
}

func Exists(key string)(bool,error){
	return redis.Bool(DefaultRedisConn.Do("EXISTS",key))
}

func Get(key string)(string,error){
	return redis.String(DefaultRedisConn.Do("GET",key))
}

func Count(key string)(int,error){
	return redis.Int(DefaultRedisConn.Do("GET",key))
}

func Del(key string)error{
	_,err:= DefaultRedisConn.Do("DEL",key)
	if err!=nil{
		return err
	}
	return nil
}

func Incr(key string)error{
	_,err:= DefaultRedisConn.Do("INCR",key)
	if err!=nil{
		return err
	}
	return nil
}

// todo insert和update分开：insert自增，update不自增
func HSet(key , field,value interface{})error{
	_,err:= DefaultRedisConn.Do("HSET",key, field,value)
	return err
}


func main() {
	var err error
	DefaultRedisConn, err = redis.Dial("tcp", "127.0.0.1:6379")
	if err != nil {
		fmt.Println("Connect to redis error", err)
		return
	}
	defer DefaultRedisConn.Close()

	_, err = DefaultRedisConn.Do("SET", "mykey", "superWang")
	if err != nil {
		fmt.Println("redis set failed:", err)
	}

	username, err := redis.String(DefaultRedisConn.Do("GET", "mykey"))
	if err != nil {
		fmt.Println("redis get failed:", err)
	} else {
		fmt.Printf("Get mykey: %v \n", username)
	}
	initArticle(1)
	viewCount, err := redis.String(DefaultRedisConn.Do("GET", getBlogPageViewKeys(1)))
	fmt.Println(viewCount)
	for i:=0;i<1000;i++{
		view(1)
		viewCount, err = redis.String(DefaultRedisConn.Do("GET", getBlogPageViewKeys(1)))
		fmt.Println(viewCount)
	}

}


func initArticle(blogId int){
	//c.conn.Do("SET",getBlogPageViewKeys(blogId),"0")
	DefaultRedisConn.Do("SET",getBlogPageViewKeys(blogId),"0")
}

func view(blogId int){
	DefaultRedisConn.Do("INCR",getBlogPageViewKeys(blogId))
}

func getBlogPageViewKeys(articleId int)string{
	return "blog:"+strconv.Itoa(articleId)+":viewCount"

}